package com.iceclean.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iceclean.po.*;
import com.iceclean.service.PostBarService;
import com.iceclean.serviceImpl.PostBarServiceImpl;
import com.iceclean.util.ServiceAgent;

import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * @author : Ice'Clean
 * @date : 2021-05-07
 *
 * 接收所有与贴吧操作有关的请求
 */
@WebServlet(name = "PostBarServlet", value = "/PostBarServlet")
public class PostBarServlet extends BaseServlet {

    public static final String AGREE = "agree";
    public static final String REJECT = "reject";

    /**
     * 贴吧服务的动态代理
     */
    PostBarService postBarService = (PostBarService) new ServiceAgent(new PostBarServiceImpl()).getAgent();

    /**
     * 创建贴吧
     */
    public void createPostBar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int userId = Integer.parseInt(request.getParameter("userId"));
        String postBarName = request.getParameter("postBarName");
        String postBarResume = request.getParameter("postBarResume");

        // 判断贴吧名是否已存在
        response.setContentType("text/html;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        if (postBarService.findPostBarByName(postBarName) == null) {
            // 创建新贴吧，并将贴吧实体发送给给前端
            PostBar postBar = postBarService.createPostBar(userId, postBarName, postBarResume);
            HttpSession session = request.getSession();
            session.setAttribute("postBar", postBar);
            response.getWriter().write(mapper.writeValueAsString(postBar));
        }else {
            // 返回空贴吧
            response.getWriter().write(mapper.writeValueAsString(new PostBar()));
        }
    }

    /**
     * 系统管理员审核创建贴吧
     * agree 表示审核通过，reject 表示审核不通过
     * 审核通过则将贴吧 check 字段改为 1，不通过则删除此贴吧记录
     */
    public void checkCreatePostBar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取对应的贴吧 id、审核信息
        int postBarId = Integer.parseInt(request.getParameter("postBarId"));
        String checkMessage = request.getParameter("checkMessage");

        boolean isSuccess;
        if (AGREE.equals(checkMessage)) {
            // 执行审核通过服务
            isSuccess = postBarService.agreeCreatePostBar(postBarId);
        } else {
            isSuccess = postBarService.deletePostBar(postBarId);
        }


        response.getWriter().write("" + isSuccess);
    }

    /**
     * 获取 session 中的贴吧，即绑定了的贴吧
     */
    public void getPostBarBySession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 从 session 中取出存放的贴吧对象
        PostBar postBar =  (PostBar) request.getSession().getAttribute("postBar");
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(mapper.writeValueAsString(postBar));
    }

    /**
     * 通过 id 获取贴吧
     */
    public void getPostBarById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 贴吧列表中的超链接发过来的 Get 请求，携带了贴吧 id
        int postBarId = Integer.parseInt(request.getParameter("postBarId"));

        PostBar postBar = postBarService.findPostBarById(postBarId);
        System.out.println(postBar.getPostBarName());

        // 将获取到的贴吧对象存放到 session 中
        HttpSession session = request.getSession();
        session.setAttribute("postBar", postBar);

        // 然后跳转到贴吧页面中，贴吧页面会自动发送一个 post 请求（就是下面的 doPost），获取到刚刚存进去的贴吧对象
        response.setCharacterEncoding("utf-8");
        response.sendRedirect("html/postBarContent.html");
    }

    /**
     * 获取贴吧总数
     * 按传进来的是否审核查询
     * 传入 1 表示正在审核，查询未审核的贴吧，0 则查询已通过审核的贴吧
     */
    public void getAllPostBarForNumber(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 根据审核标记查询
        int check = Integer.parseInt(request.getParameter("check"));
        int number = postBarService.getNumberOfAllPostBar(check);

        // 返回给前端
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(""+number);
    }

    /**
     * 按页数获取贴吧
     * （1）有传进来用户 id 的，返回的贴吧为该用户创建的并且已经审核通过的
     * （2）传进来的还包含审核表示，只看审核的或者只看未审核的
     * 1 表示正在审核，只看未审核的（即系统管理员审核界面）；0 表示没有审核，只看已审核的（即贴吧列表）
     * （3）有传进来搜索 search 的，返回的贴吧是包含该内容的，能搜索到的全都是已审核的
     */
    public void getAllPostBarByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取可能存在的用户 id 和搜索字段
        String userId = request.getParameter("userId");
        String search = request.getParameter("search");

        // 获取开始和结束的下标
        int page = Integer.parseInt(request.getParameter("page"));
        int num = Integer.parseInt(request.getParameter("num"));
        System.out.println("有没有参数啊？" + userId);

        List<PostBar> postBars;

        if (userId != null) {
            // 用户查看时，查看的时已通过审核的
            postBars = postBarService.findUserPostBarByPage(Integer.parseInt(userId), page, num);
        } else if (search != null) {
            // 搜索贴吧时，查询的是已通过审核的贴吧
            postBars = postBarService.searchPostBarByPage(search, page, num);
        } else {
            // 非用户个人查看、非搜索时，区分审核标识，是只看已通过审核的还是只看未审核的
            int check = Integer.parseInt(request.getParameter("check"));
            postBars = postBarService.findPostBarsByPage(check, page, num);
        }

        response.setContentType("text/html;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(postBars));
    }

    /**
     * 获取按搜索字段搜索出来的贴吧总数
     * 只在搜索按钮被按下时执行
     */
    public void getAllSearchForNumber(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");

        // 获取对应的搜索字段
        String search = request.getParameter("search");

        int number = postBarService.getAllSearchForNumber(search);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(""+number);
    }

    /**
     * 改变贴吧的关注数（关注 / 取消关注）
     */
    public void changePostBarFollow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取关注相关的贴吧和用户（已绑定的）
        PostBar postBar = (PostBar) request.getSession().getAttribute("postBar");
        User user = (User) request.getSession().getAttribute("user");

        // 执行关注操作
        PostBarFollow postBarFollow = postBarService.changePostBarFollow(postBar.getPostBarId(), user.getUserId());

        // 判断是新建关注还是取消关注，然后返回给前端
        response.setContentType("text/html;charset=utf-8");
        if (postBarFollow == null) {
            // 为 null 说明该操作为取消关注
            // 贴吧关注数 -1
            postBar.setPostBarFollow(postBar.getPostBarFollow() - 1);
            request.getSession().setAttribute("postBar", postBar);
            // 用户关注贴吧数 -1
            user.setFollowPostBar(user.getFollowPostBar() - 1);
            request.getSession().setAttribute("user", user);
            response.getWriter().write("cancel");
        } else {
            // 否则为新建点赞
            // 贴吧关注数 -1
            postBar.setPostBarFollow(postBar.getPostBarFollow() + 1);
            request.getSession().setAttribute("postBar", postBar);
            // 用户关注贴吧数 +1
            user.setFollowPostBar(user.getFollowPostBar() + 1);
            request.getSession().setAttribute("user", user);
            response.getWriter().write("create");
        }
    }

    /**
     * 按页数获取用户关注的贴吧
     */
    public void getAllPostBarFollowByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取绑定的用户
        int userId = Integer.parseInt(request.getParameter("userId"));

        // 按页数获取贴吧
        // 获取开始和结束的下标
        int page = Integer.parseInt(request.getParameter("page"));
        int num = Integer.parseInt(request.getParameter("num"));

        List<PostBar> postBarList = postBarService.findPostBarFollowByPage(userId, page, num);

        response.setContentType("text/html;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(postBarList));
    }

    /**
     * 检查用户是否已经关注过
     */
    public void isUserFollowPostBar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取到当前贴吧和用户
        PostBar postBar = (PostBar) request.getSession().getAttribute("postBar");
        User user = (User) request.getSession().getAttribute("user");

        // 判断用户是否已经收藏过
        boolean isUserFollowPostBar = postBarService.isUserFollowPostBar(postBar.getPostBarId(), user.getUserId());

        // 返回给前端
        response.getWriter().write("" + isUserFollowPostBar);
    }
}
